import router from "@/router"
import { useAppStore, useAuthStore } from "@/store"
import { useToken } from "./useToken"
import { isEmpty, useCommonNotification } from "@/utils"
import { api } from "@/api/auth"
import { authorizationSettings } from "@/settings/authorization-settings"
const notification = useCommonNotification()

/**
 * 登录、鉴权
 */
const settings = ref({ ...authorizationSettings })
const { setToken, getAccessToken, clearToken, hasToken } = useToken()

export function tokenInfo() {
    const token = getAccessToken()
    return {
        authorizationHeader: settings.value.accessToken,
        authorizationValue: isEmpty(token) ? undefined : `${settings.value.accessTokenPrefix} ${token}`
    }
}

export async function doLogin(username: string, password: string) {
    const { res, isOk } = await api.login({ username, password })
    if (isOk()) {
        setToken(res.value)
        const { setting } = storeToRefs(useAppStore())
        notification.success({ title: "登录成功", description: `欢迎使用${setting.value.sysName}` })
        router.push({ name: settings.value.welcomeViewName })
    }
}

export async function checkLogin() {
    const { res, isOk } = await api.checkLogin()
    if (isOk()) {
        const { login } = useAuthStore()
        const { user, permissions, menus } = res.value
        const authUser = { name: user.nickname, avatar: user.avatar }
        const authPermissions = (permissions ?? []) as string[]
        const authMenus = menus ?? []
        login(authUser, authPermissions, authMenus)
    }
}

export async function doLogout(server = true) {
    if (server) {
        const { isOk } = await api.logout()
        if (isOk()) {
            afterLogout()
        }
    } else {
        afterLogout()
    }
}

function afterLogout() {
    const { logout } = useAuthStore()
    clearToken()
    logout()
    router.push({ name: "Login" })
}

export { hasToken }
